package com.lyl.serviceucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyl.commonutils.DateUtils;
import com.lyl.commonutils.JwtUtils;
import com.lyl.commonutils.MD5;
import com.lyl.commonutils.redis.RedisConstants;
import com.lyl.commonutils.redis.RedisUtils;
import com.lyl.exception.ZxjyException;
import com.lyl.serviceucenter.entity.Member;
import com.lyl.serviceucenter.entity.vo.LoginVo;
import com.lyl.serviceucenter.entity.vo.RegisterVo;
import com.lyl.serviceucenter.mapper.MemberMapper;
import com.lyl.serviceucenter.service.MemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author 雷艳玲
 * @since 2022-06-18
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {
    @Autowired
     RedisTemplate<String, String> redisTemplate;

    @Autowired
    MemberMapper memberMapper;

    /**
     * 会员登录
     * @param loginVo
     * @return
     */
    @Override
    public String login(LoginVo loginVo) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();

        //校验参数
        if(StringUtils.isEmpty(mobile) ||
                StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(mobile)) {
            throw new ZxjyException(20001,"error");
        }

        //获取会员
        Member member = baseMapper.selectOne(new QueryWrapper<Member>().eq("mobile", mobile));
        if(null == member) {
            throw new ZxjyException(20001,"该账户不存在");
        }

        //校验密码
        if(!MD5.encrypt(password).equals(member.getPassword())) {
            throw new ZxjyException(20001,"用户名或密码错误");
        }

        //校验是否被禁用
        if(member.getIsDisabled()) {
            throw new ZxjyException(20001,"该用户已被禁用");
        }

        //使用JWT生成token字符串
        String token = JwtUtils.getJwtToken(member.getId().toString(), member.getNickname());
        return token;
    }
    @Override
    public LoginVo getLoginInfo(String memberId) {
        Member member = baseMapper.selectById(memberId);
        LoginVo loginInfoVo = new LoginVo();
        BeanUtils.copyProperties(member, loginInfoVo);
        return loginInfoVo;
    }

    @Override
    public Member getByOpenid(String openid) {

        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid", openid);

        Member member = baseMapper.selectOne(queryWrapper);
        return member;
    }

    @Override
    public String loginByCode(LoginVo loginVo) {
        String mobile=loginVo.getMobile();
        String code= loginVo.getCode();
        //校验参数
        if(StringUtils.isEmpty(mobile) ||
                StringUtils.isEmpty(code) ) {
            throw new ZxjyException(20001,"用户名和验证码不能为空");
        }

        //获取会员
        Member member = baseMapper.selectOne(new QueryWrapper<Member>().eq("mobile", mobile));
        if(null == member) {
            throw new ZxjyException(20001,"该账户不存在");
        }

        //校验密码
        String redisCode = redisTemplate.opsForValue().get(mobile);
        if(redisCode==null || !(code.equals(redisCode))){
            throw new ZxjyException(20001,"验证码错误");
        }

        //校验是否被禁用
        if(member.getIsDisabled()) {
            throw new ZxjyException(20001,"该用户已被禁用");
        }

        //使用JWT生成token字符串
        String token = JwtUtils.getJwtToken(member.getId().toString(), member.getNickname());
        return token;
    }

    @Override
    public Long getMemberCountByDay(String date) {
        return memberMapper.getMemberCountByDay(date);
    }

    @Override
    public String bindPhone(String openId, String phone, String code) {

        // 验证码存放1号库
        RedisUtils.setDataBase(redisTemplate,1);
        if(!redisTemplate.opsForValue().get(phone).equals(code)){
            throw  new ZxjyException(20001,"验证码错误");
        }


        // 查看此电话号码之前是否已经注册过
        QueryWrapper<Member> memberQueryWrapper= new QueryWrapper<>();
        memberQueryWrapper.eq("mobile",phone);
        Member phoneMember = memberMapper.selectOne(memberQueryWrapper);


        System.out.println("phone:-->"+phone);

        QueryWrapper<Member> openIdQuery= new QueryWrapper<>();
        openIdQuery.eq("openid",openId);
        System.out.println("openId-->"+openId);
        Member openIdMember = memberMapper.selectOne(openIdQuery);
        System.out.println("openIdMember:--->"+openIdMember);

        if(phoneMember!=null){// 该手机号码已经注册过了, 把open跟这个数据合并

//            openIdMember.setPassword(phoneMember.getPassword());

//            phoneMember.setMobile("");
//            phoneMember.setIsDeleted(1);
            phoneMember.setOpenid(openId);
            memberMapper.updateById(phoneMember);

            openIdMember.setOpenid("");
            memberMapper.updateById(openIdMember);
        }else{
            openIdMember.setMobile(phone);
            memberMapper.updateById(openIdMember);
        }


        // 生成jwt
        String token = JwtUtils.getJwtToken(openIdMember.getId().toString(),openIdMember.getNickname());


        return token;
    }

    @Override
    public void pageQuery(Page<Member> pageParam, Member member) {
        QueryWrapper<Member> queryWrapper= new QueryWrapper<>();
        queryWrapper.orderByDesc("gmt_create");

        if (member == null){
            baseMapper.selectPage(pageParam, queryWrapper);
            return;
        }

        String mobile = member.getMobile();
        String nickname = member.getNickname();

        if (!StringUtils.isEmpty(mobile)) {
            queryWrapper.like("mobile", mobile);
        }

        if (!StringUtils.isEmpty(nickname) ) {
            queryWrapper.eq("nickname", nickname);
        }



        baseMapper.selectPage(pageParam, queryWrapper);
    }

    @Override
    public boolean updateStatusById(Long id, Boolean bannerStatus) {
        Member member= new Member();
        member.setId(id);
        member.setIsDisabled(bannerStatus);

        return  baseMapper.updateById(member)>0;
    }


    /**
     * 会员注册
     * @param registerVo
     */
    @Override
    public boolean register(RegisterVo registerVo) {
        //获取注册信息，进行校验
        String nickname = registerVo.getNickname();
        String mobile = registerVo.getMobile();
        String password = registerVo.getPassword();
        String code = registerVo.getCode();

        //校验参数
        if(StringUtils.isEmpty(mobile) ||
                StringUtils.isEmpty(mobile) ||
                StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(code)) {
            throw new ZxjyException(20001,"error");
        }

        //校验校验验证码
        //从redis获取发送的验证码
        String mobleCode = redisTemplate.opsForValue().get(mobile);
        if(!code.equals(mobleCode)) {
            throw new ZxjyException(20001,"验证码错误");
        }

        //查询数据库中是否存在相同的手机号码
        Integer count = baseMapper.selectCount(new QueryWrapper<Member>().eq("mobile", mobile));
        if(count.intValue() > 0) {
            throw new ZxjyException(20001,"该账号已被注册");
        }

        //添加注册信息到数据库
        Member member = new Member();
        member.setNickname(nickname);
        member.setMobile(registerVo.getMobile());
        member.setPassword(MD5.encrypt(password));
        member.setIsDisabled(false);
        // 设置默认头像 默认都是王心凌
        member.setAvatar("https://zxjy-tx.oss-cn-shenzhen.aliyuncs.com/avatar/c510b43b-f952-4fc0-8603-eed7ceba7bdf.jpg");

        return this.save(member);
    }



}
